import socket
import time
import keyboard
import pyautogui

# 设置服务器地址和端口
server_address = ('0.0.0.0', 5000)  # 监听所有网络接口上的5000端口

# 创建一个 TCP/IP 套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 绑定服务器地址和端口
sock.bind(server_address)

# 监听端口，等待客户端连接
sock.listen(1)
print("等待 Waffle Nano 连接...")

# 接受连接
connection, client_address = sock.accept()
print(f"连接已建立，客户端地址: {client_address}")

current_mode = "water"  # 初始模式为 "water"
last_left_time = 0
last_right_time = 0
left_pressed = False
right_pressed = False
mouse_left_down = False

def switch_mode():
    global current_mode
    if current_mode == "water":
        current_mode = "fire"
    else:
        current_mode = "water"
    print(f"模式已切换为: {current_mode}")

# 监听 C 键用于切换模式
keyboard.add_hotkey('c', switch_mode)

try:
    while True:
        # 接收数据
        data = connection.recv(1024)
        if data:
            commands = data.decode('utf-8').strip().splitlines()  # 使用换行符分隔命令
            for command in commands:
                print(f"接收到原始数据: {command}")

                if command.startswith("mouse:"):
                    print("鼠标移动数据:")
                    cmd = command[6:]
                    if "mouse_move" in cmd:
                        parts = cmd.split(",")
                        if len(parts) == 3:  # 确保有三个部分
                            try:
                                x_move = int(parts[1])
                                y_move = int(parts[2])
                                pyautogui.moveRel(x_move, y_move, duration=0.1)
                            except ValueError:
                                print(f"解析鼠标移动数据时出错: {cmd}")
                        else:
                            print(f"命令格式错误: {cmd}")
                    elif cmd == "mouse_left_down":
                        if not mouse_left_down:
                            pyautogui.mouseDown(button='left')
                            mouse_left_down = True
                    elif cmd == "mouse_left_up":
                        if mouse_left_down:
                            pyautogui.mouseUp(button='left')
                            mouse_left_down = False
                    elif cmd == "mouse_right_click":
                        pyautogui.click(button='right')
                    elif cmd == "mouse_middle_click":
                        pyautogui.click(button='middle')

                elif command.startswith("character:"):
                    print("人物移动数据:")

                    cmd = command[10:]
                    current_time = time.time()
                    if cmd=='switch_mode':
                        switch_mode()
                    if current_mode == "water":
                        if cmd == 'right':
                            last_right_time = current_time
                            if not right_pressed:
                                keyboard.press('d')
                                right_pressed = True
                            if left_pressed:
                                keyboard.release('a')
                                left_pressed = False
                        elif cmd == 'left':
                            last_left_time = current_time
                            if not left_pressed:
                                keyboard.press('a')
                                left_pressed = True
                            if right_pressed:
                                keyboard.release('d')
                                right_pressed = False
                        elif cmd == 'up':
                            keyboard.press('w')
                            time.sleep(0.3)
                            keyboard.release('w')
                        elif cmd == 'down':
                            if right_pressed:
                                keyboard.release('d')
                                right_pressed = False
                            if left_pressed:
                                keyboard.release('a')
                                left_pressed = False
                    elif current_mode == "fire":
                        if cmd == 'right':
                            last_right_time = current_time
                            if not right_pressed:
                                keyboard.press('right')
                                right_pressed = True
                            if left_pressed:
                                keyboard.release('left')
                                left_pressed = False
                        elif cmd == 'left':
                            last_left_time = current_time
                            if not left_pressed:
                                keyboard.press('left')
                                left_pressed = True
                            if right_pressed:
                                keyboard.release('right')
                                right_pressed = False
                        elif cmd == 'up':
                            keyboard.press('up')
                            time.sleep(0.3)
                            keyboard.release('up')
                        elif cmd == 'down':
                            if right_pressed:
                                keyboard.release('right')
                                right_pressed = False
                            if left_pressed:
                                keyboard.release('left')
                                left_pressed = False

                # 如果超过 0.3 秒没有收到 left/right 指令，释放按键
                if right_pressed and current_time - last_right_time > 0.3:
                    keyboard.release('d' if current_mode == "water" else 'right')
                    right_pressed = False

                if left_pressed and current_time - last_left_time > 0.3:
                    keyboard.release('a' if current_mode == "water" else 'left')
                    left_pressed = False

        else:
            # 如果没有接收到数据，继续等待
            print("等待数据传输...")
            time.sleep(1)
except Exception as e:
    print(f"连接中断，错误: {e}")
finally:
    # 关闭连接
    connection.close()
    sock.close()  # 关闭服务器套接字
